<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 表单区域 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isTrue"
          loading-text="登录中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入网络请求
import { loginAPI } from "@/api";
export default {
  data() {
    return {
      mobile: "",
      code: "",
      rules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "onBulr" },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "请输入正确的手机号",
            trigger: "onBulr",
          },
        ],
        code: [
          { required: true, message: "请填写验证码", trigger: "onBulr" },
          { pattern: /^\d{6}$/, message: "验证码长度为6", trigger: "onBulr" },
        ],
      },
      isTrue: false,
    };
  },

  methods: {
    async onSubmit(data) {
      this.isTrue = true;
      try {
        // 提交数据到服务器
        const res = await loginAPI(data);
        // 提示登录成功
        this.$toast.success("登录成功");
        // 保存token
        this.$store.commit("setToken", res.data.data);
        // 跳转页面
        const url = this.$route.query.url;
        if (url) {
          this.$router.push(url);
        } else {
          this.$router.push("layout/home");
        }
      } catch {
        this.$toast.fail("登录失败");
      } finally {
        this.isTrue = false;
      }
      // .then((res) => {
      //   this.$toast.success("登录成功");
      // })
      // .catch((err) => {
      //   this.$toast.fail("登录失败");
      // })
      // .finally(() => {
      //   this.isTrue = false;
      // });
    },
  },
};
</script>

<style>
</style>